import React, { Fragment } from 'react';
import { renderToString } from 'react-dom/server'
import { Provider } from 'react-redux'
import { getServerStore } from '../store'
import { renderRoutes, matchRoutes } from 'react-router-config'
import { StaticRouter, Route, matchPath } from 'react-router-dom'  // matchPath 是匹配路径的。
import Header from '../containers/header/index.js'
import routes from '../routes'

export default function (req, res) {
    // let matchRoutes = routes.filter(route=>{
    //     return matchPath(req.path, route);
    // })
    // matchRoutes 可以处理嵌套路由
    let matchedRoutes = matchRoutes(routes, req.path);
    let store = getServerStore();
    let promise = []
    matchedRoutes.forEach(item => {
        if (item.loadData) promise.push(item.loadData(store))
    })
    Promise.all(promise).then(() => {
        let htm = renderToString(
            <Provider store={store}>
                <StaticRouter context={{ name: 'hong hong' }} location={req.path}>
                    {renderRoutes(routes)}
                    {/* {routes.map((item) => {
                            return <Route {...item} />
                        })} */}
                </StaticRouter>
            </Provider>
        )

        res.send(
            `
                <html>
                    <head>
                        <tittle>react</tittle>
                    </head>
                    <body>
                        <div id="root">${htm}</div>
                        <script>
                            window.context = {
                                state: ${JSON.stringify(store.getState())}
                            }
                        </script>
                        <script src="/client.js"></script>
                    </body>
                </html>
            `
        )
    })
}

